/*
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * DMGIS. You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with DMGIS.
 *
 */
package com.dmgis.qxfw.dataservice.businessservice.yygt.controller;


import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.smallscale_station;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.dispoint_monitor_info;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.potential_points;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.radar_warn_monitor_info;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.warn_moni_info;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.*;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.*;
import com.dmgis.qxfw.dataservice.businessservice.common.service.IConfigService;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.FileRequestService;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.IQxSmallScaleService;
import com.dmgis.qxfw.dataservice.businessservice.yygt.service.IGuoTuService;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.geom.Point2D;
import java.io.File;
import java.util.*;

@Controller
@RequestMapping("/xtgt")
public class GuoTuController {
    private  final String operatingSystem;

    @Autowired
    public GuoTuController(String operatingSystem) {
        this.operatingSystem = operatingSystem;
    }
    @Resource
    private IGuoTuService guoTuService;
    @Resource
    private IConfigService configService;

    @Resource
    private ITransformService transformService;

    @Resource
    private IQxSmallScaleService skInfoService;

    //MongoService1 ms = new MongoService1();
    FileRequestService ms = new FileRequestService();


    /**
     * 初始化地灾查询界面
     *
     * @return
     * @author dsq
     * @date 2018年7月10日
     */
    @RequestMapping("/initDZQueryPage")
    @ResponseBody
    public Object initDZQueryPage() {
        ArrayList<String> result = new ArrayList<String>();
        DateTime endDate = new DateTime(guoTuService.getDZNewDate());
        result.add(endDate.AddDays(-600).toDateStringf());
        result.add(endDate.toDateStringf());
        return result;
    }

    /**
     * 获取地灾预警信息
     *
     * @param request
     * @param model
     * @return
     * @throws Exception
     * @author dsq
     * @date 2018年7月10日
     */
    @RequestMapping("/getDZInfo")
    @ResponseBody
    public Object getDZInfo(HttpServletRequest request, Model model) throws Exception {
        String startDate = request.getParameter("startDate")+ ":00:00";
        String endDate = request.getParameter("endDate")+ ":59:59";
        String type = request.getParameter("type");
        DZQuery dzQuery = new DZQuery();
        dzQuery.setStartDate(startDate);
        dzQuery.setEndDate(endDate);
        dzQuery.setType(type);
        List<DZWarning> result = guoTuService.getDZInfo(dzQuery);
        // 兰伯特转经纬度
        for (DZWarning dzWarning : result) {
            if (dzWarning.getGradeArea2() != null && !dzWarning.getGradeArea2().equals("")) {
                dzWarning.setWarLevel("蓝色预警");
            }
            if (dzWarning.getGradeArea3() != null && !dzWarning.getGradeArea3().equals("")) {
                dzWarning.setWarLevel("黄色预警");
            }
            if (dzWarning.getGradeArea4() != null && !dzWarning.getGradeArea4().equals("")) {
                dzWarning.setWarLevel("橙色预警");
            }
            if (dzWarning.getGradeArea5() != null && !dzWarning.getGradeArea5().equals("")) {
                dzWarning.setWarLevel("红色预警");
            }

            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            if (!StringUtil.IsNullOrEmpty(dzWarning.getPos())) {
                String[] posArr = dzWarning.getPos().split("\\*");
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
//                        Se_dtstj dst1 = new Se_dtstj();
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = pos.split("#")[0];
                        // 16进制颜色
                        cEntity.setColor(strColor);
                        String[] dotset = pos.split("#")[1].split(",");
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            // DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            // DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            //MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            MyPoint dm = new MyPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            tempPos.add(dm);
                            ii++;
                        }
                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                dzWarning.setPos(dzWarning.getPos());
//				Collections.sort(cEntities, new SortByColor());
                dzWarning.setEntites(cEntities);
            }

            Date date = dzWarning.getDateChar();
            dzWarning.setDate(new DateTime(date).toDateString());
            dzWarning.setDateChar(null);
            // 文件处理
        }
        return result;
    }

    /**
     * 获取地灾预警信息 最新
     *
     * @param request
     * @param model
     * @return
     * @throws Exception
     * @author qxy
     * @date 2020-06-16
     */
    @RequestMapping("/GetDZWarningNewest")
    @ResponseBody
    public Object GetDZWarningNewest(HttpServletRequest request, Model model) throws Exception {
        List<DZWarning> result = guoTuService.GetDZWarningNewest();
        // 兰伯特转经纬度
        for (DZWarning dzWarning : result) {
            if (dzWarning.getGradeArea2() != null && !dzWarning.getGradeArea2().equals("")) {
                dzWarning.setWarLevel("蓝色预警");
            }
            if (dzWarning.getGradeArea3() != null && !dzWarning.getGradeArea3().equals("")) {
                dzWarning.setWarLevel("黄色预警");
            }
            if (dzWarning.getGradeArea4() != null && !dzWarning.getGradeArea4().equals("")) {
                dzWarning.setWarLevel("橙色预警");
            }
            if (dzWarning.getGradeArea5() != null && !dzWarning.getGradeArea5().equals("")) {
                dzWarning.setWarLevel("红色预警");
            }
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            if (!StringUtil.IsNullOrEmpty(dzWarning.getPos())) {
                String[] posArr = dzWarning.getPos().split("\\*");
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = pos.split("#")[0];
                        // 16进制颜色
                        cEntity.setColor(strColor);
                        String[] dotset = pos.split("#")[1].split(",");
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                dzWarning.setPos(dzWarning.getPos());
                dzWarning.setEntites(cEntities);
            }

            Date date = dzWarning.getDateChar();
            dzWarning.setDate(new DateTime(date).toDateString());
            dzWarning.setDateChar(null);
            // 文件处理
        }
        return result;
    }


    /**
     * 获取地灾地区预警文档信息
     *
     * @param request
     * @param model
     * @return
     * @throws Exception
     * @author dsq
     * @date 2018年7月10日
     */
    @RequestMapping("/getDZAreaDoc")
    @ResponseBody
    public Object getDZAreaDoc(HttpServletRequest request, Model model) throws Exception {
        String docid = request.getParameter("docid");
        List<DZWarning> result = guoTuService.getDZAreaDoc(docid);
        // 兰伯特转经纬度
        for (DZWarning dzWarning : result) {
            if (dzWarning.getGradeArea2() != null && !dzWarning.getGradeArea2().equals("")) {
                dzWarning.setWarLevel("蓝色预警");
            }
            if (dzWarning.getGradeArea3() != null && !dzWarning.getGradeArea3().equals("")) {
                dzWarning.setWarLevel("黄色预警");
            }
            if (dzWarning.getGradeArea4() != null && !dzWarning.getGradeArea4().equals("")) {
                dzWarning.setWarLevel("橙色预警");
            }
            if (dzWarning.getGradeArea5() != null && !dzWarning.getGradeArea5().equals("")) {
                dzWarning.setWarLevel("红色预警");
            }
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            if (!StringUtil.IsNullOrEmpty(dzWarning.getPos())) {
                String[] posArr = dzWarning.getPos().split("\\*");
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = pos.split("#")[0];
                        // 16进制颜色
                        cEntity.setColor(strColor);
                        String[] dotset = pos.split("#")[1].split(",");
                        int ii = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            ii++;
                        }
                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
                dzWarning.setPos(dzWarning.getPos());
                dzWarning.setEntites(cEntities);
            }

            Date date = dzWarning.getDateChar();
            dzWarning.setDate(new DateTime(date).toDateString());
            dzWarning.setDateChar(null);
            // 文件处理
        }
        return result;
    }

    /**
     * 显示地灾信息文档路径
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/showDoc")
    @ResponseBody
    public String showDoc(HttpServletRequest request, Model model) {
        String servicePath = "";
        String docPath = request.getParameter("docpath");


        if (docPath == null || docPath.equals("")) {
            return "";
        }
        String id = guoTuService.getProductID(docPath);// 获取编号
        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\gtWarning\\";
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/gtWarning/";
        }

        String path = request.getContextPath();
        String basePath = DbConfig.IP + path;
        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当文件达到100张时清除
        FileUtil.ClearTempFiles(urlpath, 100);
        String fileName = docPath.split("\\\\")[docPath.split("\\\\").length - 1];
        String docType = fileName.split("\\.")[fileName.split("\\.").length - 1];
        // 判断文件类型是否是word
        if (docType.contains("doc")) {
            String pdfPath = urlpath + fileName.replace(docType, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                if (operatingSystem.equals("Windows")){
                    servicePath = "\\Temp\\gtWarning\\" + fileName.replace(docType, "pdf");
                }else {
                    servicePath = "/Temp/gtWarning/" + fileName.replace(docType, "pdf");
                }

                servicePath = basePath+servicePath;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "base_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                // 下载doc文件
                if (data == null) {
                    return "";
                }
                FileUtil.bytesToFile(data, pdfPath);
                if (operatingSystem.equals("Windows")){
                    servicePath = "\\Temp\\gtWarning\\" + fileName.replace(docType, "pdf");
                }else {
                    servicePath = "/Temp/gtWarning/" + fileName.replace(docType, "pdf");
                }

                servicePath = basePath+servicePath;
            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }

    /**
     * 初始化灾点查询页面
     *
     * @return
     * @author dsq
     * @date 2018年7月27日
     */
    @RequestMapping("/initDisPointPage")
    @ResponseBody
    public Object initDisPointPage() {
        List<String> countys = new ArrayList<String>();
        List<potential_points> countyList = configService.getCountry();
        for (potential_points county : countyList) {
            String countyName = county.getCounty().trim();
            countys.add(countyName);
        }
        return countys;
    }

    /**
     * 查询地灾隐患点
     *
     * @param request
     * @param model
     * @return
     * @author dsq
     * @date 2018年7月27日
     */
    @RequestMapping("/getDisPoint")
    @ResponseBody
    public Object getDisPoint(HttpServletRequest request, Model model) {
        String disId = request.getParameter("disId");
        String disName = request.getParameter("disName");
        String county = request.getParameter("county");
        String disType = request.getParameter("disType");
        String level = request.getParameter("level");
        String disLevel = request.getParameter("disLevel");
        String population = request.getParameter("population");
        String populationTo = request.getParameter("populationTo");
        String property = request.getParameter("property");
        String propertyTo = request.getParameter("propertyTo");
        DisPointSearch disPointSearch = new DisPointSearch();
        disPointSearch.setDisId(disId);
        disPointSearch.setDisName(disName);
        disPointSearch.setCounty(county);
        disPointSearch.setDisType(disType);
        disPointSearch.setLevel(level);
        disPointSearch.setDisLevel(disLevel);

        if (!(StringUtil.IsNullOrEmpty(population) || StringUtil.IsNullOrEmpty(populationTo))) {
            disPointSearch.setPopulation(Integer.parseInt(population));
            disPointSearch.setPopulationTo(Integer.parseInt(populationTo));
        }
        if (!(StringUtil.IsNullOrEmpty(property) || StringUtil.IsNullOrEmpty(propertyTo))) {
            disPointSearch.setProperty(Integer.parseInt(property));
            disPointSearch.setPropertyTo(Integer.parseInt(propertyTo));
        }
        List<potential_points> disPoints = guoTuService.selectDisPoint(disPointSearch);
        List<DPoint> resultList = new ArrayList<DPoint>();
        for (int i = 0; i < disPoints.toArray().length; i++) {
            Double lon = WebCtrlData.Getddformddffmm(Double.parseDouble(disPoints.get(i).getLon().toString()));
            Double lat = WebCtrlData.Getddformddffmm(Double.parseDouble(disPoints.get(i).getLat().toString()));
//            DmMapPoint dt = transformService.LonLatConvertToLambert(lon, lat);
            DPoint dPoint = new DPoint();
            dPoint.setLon(lon);
            dPoint.setLat(lat);
            dPoint.setPp_id(disPoints.get(i).getPp_id().trim());
            dPoint.setField_id(disPoints.get(i).getField_id().trim());
            dPoint.setContact(disPoints.get(i).getContact().trim());
            dPoint.setContact_tel(disPoints.get(i).getContact_tel().trim());
            dPoint.setContact1(disPoints.get(i).getContact1().trim());
            dPoint.setContact1_tel(disPoints.get(i).getContact1_tel().trim());
            dPoint.setGeo_addr(disPoints.get(i).getGeo_addr().trim());
            dPoint.setHappen_year(disPoints.get(i).getHappen_year().trim());
            dPoint.setHappen_month(disPoints.get(i).getHappen_month().trim());
            dPoint.setHappen_day(disPoints.get(i).getHappen_day().trim());
            dPoint.setDeath_toll(disPoints.get(i).getDeath_toll());
            dPoint.setDirect_loss(disPoints.get(i).getDirect_loss());
            dPoint.setCur_state(disPoints.get(i).getCur_state().trim());
            dPoint.setStationName(disPoints.get(i).getPp_name().trim());
            dPoint.setPp_name(disPoints.get(i).getPp_name().trim());
            dPoint.setDis_scale(disPoints.get(i).getDis_scale().trim());
            dPoint.setDis_type(disPoints.get(i).getDis_type().trim());
            dPoint.setDis_level(disPoints.get(i).getDis_level().trim());
            dPoint.setDanger_level(disPoints.get(i).getDanger_level().trim());
            dPoint.setAttention_level(disPoints.get(i).getAttention_level().trim());
            dPoint.setEasyissue_level(disPoints.get(i).getEasyissue_level().trim());
            dPoint.setThreat_pop(disPoints.get(i).getThreat_pop());
            dPoint.setThreat_prop(disPoints.get(i).getThreat_prop());
            resultList.add(dPoint);
        }
        return resultList;
    }


    /**
     * 查询地灾隐患点
     *
     * @param request
     * @param model
     * @return
     * @author dsq
     * @date 2018年7月27日
     */
    @RequestMapping("/getDisPointrisk")
    @ResponseBody
    public Object getDisPointrisk(HttpServletRequest request, Model model) {
        String scope = request.getParameter("scope");// 半径
        String d = request.getParameter("d");
        String f = request.getParameter("f");
        String m = request.getParameter("m");
        String d1 = request.getParameter("d1");
        String f1 = request.getParameter("f1");
        String m1 = request.getParameter("m1");
        Double lon2 = WebCtrlData.ToDegress(d, f, m);
        Double lat2 = WebCtrlData.ToDegress(d1, f1, m1);

        String disId = request.getParameter("disId");
        String disName = request.getParameter("disName");
        String county = request.getParameter("county");
        String disType = request.getParameter("disType");
        String level = request.getParameter("level");
        String disLevel = request.getParameter("disLevel");
        String population = request.getParameter("population");
        String populationTo = request.getParameter("populationTo");
        String property = request.getParameter("property");
        String propertyTo = request.getParameter("propertyTo");
        DisPointSearch disPointSearch = new DisPointSearch();
        disPointSearch.setDisId(disId);
        disPointSearch.setDisName(disName);
        disPointSearch.setCounty(county);
        disPointSearch.setDisType(disType);
        disPointSearch.setLevel(level);
        disPointSearch.setDisLevel(disLevel);
        if (!(StringUtil.IsNullOrEmpty(population) || StringUtil.IsNullOrEmpty(populationTo))) {
            disPointSearch.setPopulation(Integer.parseInt(population));
            disPointSearch.setPopulationTo(Integer.parseInt(populationTo));
        }
        if (!(StringUtil.IsNullOrEmpty(property) || StringUtil.IsNullOrEmpty(propertyTo))) {
            disPointSearch.setProperty(Integer.parseInt(property));
            disPointSearch.setPropertyTo(Integer.parseInt(propertyTo));
        }
        List<potential_points> disPoints = guoTuService.selectDisPoint(disPointSearch);
        List<DPoint> resultList = new ArrayList<DPoint>();
        int count = disPoints.toArray().length;
        for (int i = 0; i < count; i++) {
            Point2D center = new Point2D.Double(lon2, lat2);
            Point2D yidong = new Point2D.Double(Double.parseDouble( disPoints.get(i).getLon())  ,Double.parseDouble( disPoints.get(i).getLat()));
            if (getDistance(center, yidong) < Double.parseDouble(scope)) {
                Double lon1= WebCtrlData.Getddformddffmm(Double.parseDouble(disPoints.get(i).getLon().toString()));
                Double lat1 = WebCtrlData.Getddformddffmm(Double.parseDouble(disPoints.get(i).getLat().toString()));
                DmMapPoint dt = transformService.LonLatConvertToLambert(lon1, lon2);
                DPoint dPoint = new DPoint();
                dPoint.setLon(lon1);
                dPoint.setLat(lat1);
                dPoint.setPp_id(disPoints.get(i).getPp_id().trim());
                dPoint.setField_id(disPoints.get(i).getField_id().trim());
                dPoint.setContact(disPoints.get(i).getContact().trim());
                dPoint.setContact_tel(disPoints.get(i).getContact_tel().trim());
                dPoint.setContact1(disPoints.get(i).getContact1().trim());
                dPoint.setContact1_tel(disPoints.get(i).getContact1_tel().trim());
                dPoint.setGeo_addr(disPoints.get(i).getGeo_addr().trim());
                dPoint.setHappen_year(disPoints.get(i).getHappen_year().trim());
                dPoint.setHappen_month(disPoints.get(i).getHappen_month().trim());
                dPoint.setHappen_day(disPoints.get(i).getHappen_day().trim());
                dPoint.setDeath_toll(disPoints.get(i).getDeath_toll());
                dPoint.setDirect_loss(disPoints.get(i).getDirect_loss());
                dPoint.setCur_state(disPoints.get(i).getCur_state().trim());
                dPoint.setStationName(disPoints.get(i).getPp_name().trim());
                dPoint.setPp_name(disPoints.get(i).getPp_name().trim());
                dPoint.setDis_scale(disPoints.get(i).getDis_scale().trim());
                dPoint.setDis_type(disPoints.get(i).getDis_type().trim());
                dPoint.setDis_level(disPoints.get(i).getDis_level().trim());
                dPoint.setDanger_level(disPoints.get(i).getDanger_level().trim());
                dPoint.setAttention_level(disPoints.get(i).getAttention_level().trim());
                dPoint.setEasyissue_level(disPoints.get(i).getEasyissue_level().trim());
                dPoint.setThreat_pop(disPoints.get(i).getThreat_pop());
                dPoint.setThreat_prop(disPoints.get(i).getThreat_prop());
                resultList.add(dPoint);
            }
        }
        return resultList;
    }

    /**
     * 获取气象监控信息
     *
     * @return
     * @throws Exception
     * @author dsq
     * @date 2018年8月20日
     */
    @RequestMapping("/getQxElemMoniData")
    @ResponseBody
    public Object getQxElemMoniData() throws Exception {

        String hour = configService.getSysConfig("气象要素").get(0).getParamvalue();
        if (StringUtil.IsNullOrEmpty(hour)) {
            hour = "24";
        }
        List<warn_moni_info> warnList = guoTuService.getQxElemMoniData(Integer.parseInt(hour));
        List<SmallScaleStation> stationList = configService.getTownStaList();
        List<QxElemMoniData> resultList = new ArrayList<QxElemMoniData>();
        for (warn_moni_info moni_info : warnList) {
            for (SmallScaleStation station : stationList) {
                if (moni_info.getStationid().equals(station.getStationID())) {
                    QxElemMoniData moniData = new QxElemMoniData();
                    moniData.setId(moni_info.getId());
                    moniData.setStationid(moni_info.getStationid());
                    moniData.setLon(station.getLongitude());
                    moniData.setLat(station.getLatitude());
                    DmMapPoint dmDot = new DmMapPoint(station.getLongitude(), station.getLatitude());
                    DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                    moniData.setX(ltDot.x);
                    moniData.setY(ltDot.y);
                    moniData.setMonitorvalue(moni_info.getMonitorvalue());
                    moniData.setStationName(station.getStationName());
                    moniData.setWarningtime(new DateTime(moni_info.getWarningtime()).toDateTimeString());
                    moniData.setWarningtype(moni_info.getWarningtype());
                    resultList.add(moniData);
                }

            }
        }
        // 获取预警监控信息
        return resultList;
    }

    /**
     * 获取雷达监控信息
     *
     * @return
     * @throws Exception
     * @author dsq
     * @date 2018年8月20日
     */
    @RequestMapping("/getRadarMoniData")
    @ResponseBody
    public Object getRadarMoniData(HttpServletRequest request, Model model) throws Exception {
        List<radar_warn_monitor_info> warnList = guoTuService.getRadarMoniData(3);
        List<RadarMoniData> resultList = new ArrayList<RadarMoniData>();
        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\radar\\";
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/radar/";
        }

        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当图片达到1000张时清除
        FileUtil.ClearTempFiles(urlpath, 1000);
        for (radar_warn_monitor_info moniInfo : warnList) {
            RadarMoniData moniData = new RadarMoniData();
            moniData.setElevationangle(moniInfo.getElevationangle());
            moniData.setRadarstationid(moniInfo.getRadarstationid());
            moniData.setType(moniInfo.getType());
            moniData.setWarningtime(new DateTime(moniInfo.getWarningtime()).toDateString());
            // 处理文件地址
            String filePath = moniInfo.getFilepath();
            String fileName = filePath.split("\\\\")[filePath.split("\\\\").length - 1] + ".png";
            String servicePath = urlpath + fileName;
            File serviceFile = new File(servicePath);
            if (serviceFile.exists()) {
                if (operatingSystem.equals("Windows")){
                    moniData.setFilepath("Temp\\radar\\" + fileName);
                }else {
                    moniData.setFilepath("Temp/radar/" + fileName);
                }

            } else {
                // 从mongdb获取图片
                Map<String, Object> map = new HashMap<String, Object>();
                String datechar = fileName.split("\\.")[0];
                String timechar = fileName.split("\\.")[1];
                /*datechar = datechar.substring(0, 4) + "-" + datechar.substring(4, 6) + "-" + datechar.substring(6, 8)
                        + " " + timechar.substring(0, 2) + ":" + timechar.substring(2, 4) + ":00";*/
                datechar = datechar.substring(6, 10) + "-" + datechar.substring(10, 12) + "-" + datechar.substring(12, 14)
                        + " " + "00" + ":" + "00" + ":00";
                DateTime radarDate = DateTime.parseDateTime(datechar).AddHours(8);
                map.put("datechar", radarDate.toDateString());
                map.put("stationid", moniInfo.getRadarstationid());
                map.put("elevation", String.valueOf(moniData.getElevationangle()));
                map.put("ldtype", moniData.getType());
                map.put("timechar", timechar.substring(0, 3));
                map.put("collectionName", "ld_png_file");
                byte[] data = ms.selectData(map);
                FileUtil.bytesToFile(data, servicePath);

                if (operatingSystem.equals("Windows")){
                    moniData.setFilepath("Temp\\radar\\" + fileName);
                }else {
                    moniData.setFilepath("Temp/radar/" + fileName);
                }
            }
            // 处理雷达图预警区域
            String[] warnArea = moniInfo.getWarningarea().split("\\*")[0].split(",");
            double[] pos = new double[warnArea.length];
            for (int i = 0; i < warnArea.length; i += 2) {
                DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(warnArea[i]), Double.parseDouble(warnArea[i + 1]));
                DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                pos[i] = ltDot.x;
                pos[i + 1] = ltDot.y;
            }
            moniData.setWarningarea(pos);
            resultList.add(moniData);
        }
        // 获取预警监控信息
        return resultList;
    }

    /**
     * 获取灾点数据
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/getDisPointData")
    @ResponseBody
    public  Object getDisPointData(HttpServletRequest request, Model model){
        List<dispoint_monitor_info> hiddendangerpoint = guoTuService.getHiddendangerpoint();
        return hiddendangerpoint;
    }


    /**
     * 得到山洪预警文档描述
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/getDZWarning")
    @ResponseBody
    public Object getSLWarning(HttpServletRequest request, Model model) throws Exception {
        List<DZWarning> resultList = guoTuService.getDZWarning(); //
        for (DZWarning dzWarning : resultList) {
            if (dzWarning.getGradeArea2() != null && !dzWarning.getGradeArea2().equals("")) {
                dzWarning.setWarLevel("蓝色预警");
            }
            if (dzWarning.getGradeArea3() != null && !dzWarning.getGradeArea3().equals("")) {
                dzWarning.setWarLevel("黄色预警");
            }
            if (dzWarning.getGradeArea4() != null && !dzWarning.getGradeArea4().equals("")) {
                dzWarning.setWarLevel("橙色预警");
            }
            if (dzWarning.getGradeArea5() != null && !dzWarning.getGradeArea5().equals("")) {
                dzWarning.setWarLevel("红色预警");
            }
        }

        String result = "";
        if (resultList != null && resultList.size() > 0) {
            result = new DateTime(resultList.get(0).getDateChar()).toDateString() +"：发生地质灾害" + resultList.get(0).getWarLevel();
        }
        return result;
    }

    /**
     * 初始化地灾预警查询网页
     * @return
     */

    @RequestMapping("/initDZYjQueryPage")
    @ResponseBody
    public Object initDZYjQueryPage() {
        ArrayList<String> result = new ArrayList<String>();
        DateTime endDate = new DateTime(guoTuService.getDZNewDate());//获取
        result.add(endDate.AddDays(-30).toDateTime());
        result.add(endDate.toDateTime());
        return result;
    }


    /**
     * 获取应急点
     * @author ymf
     * @date 2019/9/18
     * @param
     * @return
     **/
    @RequestMapping("/Empoint")
    @ResponseBody
    public Object getEmpoint(HttpServletRequest request, Model model) {
        String startDate = request.getParameter("startDate")+ ":00:00";;
        String endDate = request.getParameter("endDate")+ ":59:59";;
        DZQuery dzQuery = new DZQuery();
        dzQuery.setStartDate(startDate);
        dzQuery.setEndDate(endDate);
        List<Emergency> empoint = guoTuService.getEmpoint(dzQuery);
        return empoint;
    }

    /**
     * 获取某个应急点的经纬度
     * @author ymf
     * @date 2019/9/19
     * @param
     * @return
     **/
    @RequestMapping("/getemPoint")
    @ResponseBody
    public Object getemPoint(HttpServletRequest request, Model model) {
        String staName = request.getParameter("title");
        List<Emergency> resultList = new ArrayList<Emergency>();
        resultList=  guoTuService.getemPoint(staName);
        if (resultList != null && resultList.size() > 0) {
            for (Emergency srv : resultList) {
                srv.setLat(srv.getLatitude());
                srv.setLon(srv.getLongitude());
            }
        }
        return resultList;
    }

    /**
     *  初始化站点
     * @param request
     * @param model
     * @return
     */

//    @RequestMapping("/initstation")
//    @ResponseBody
//     public  Map<String, Object>  initstation(HttpServletRequest request, Model model){
//        Map<String, Object> smallScaleStation = configService.getSmallScaleStation();
//        return smallScaleStation;
//    }

    @RequestMapping("/initstation")
    @ResponseBody
    public  List<smallscale_station>  initstation(HttpServletRequest request, Model model){
        List<smallscale_station> townStaList = configService.getSmallScaleStation();
        return townStaList;
    }

    /**
     *查询乡村地灾信息
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/queryCounty")
    @ResponseBody
    public  List<TownshipStation>  getCountyInfo(HttpServletRequest request, Model model){
        String countytext = request.getParameter("countytext");
        List<TownshipStation>  countyList = guoTuService.queryCounty(countytext);
        return countyList;
    }

    /**
     * 得到灾点查询  3
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/getDPoint")
    @ResponseBody
    public Object getDPoint(HttpServletRequest request, Model model) throws Exception {
        potential_points selectKey = new potential_points();// 查询类
        String countys = request.getParameter("countys");//
        String searchParams = request.getParameter("searchParams");//
        String lon = request.getParameter("lon");
        String lat = request.getParameter("lat");
        String type = request.getParameter("type");
        selectKey.setCounty(countys);
        selectKey.setPp_name(searchParams);
        selectKey.setLon(lon);
        selectKey.setLat(lat);
        Object resultList = skInfoService.getDPoint(selectKey, type);
        return resultList;
    }
    /**
     * 通过AB点经纬度获取距离
     *
     * @param pointA A点(经，纬)
     * @param pointB B点(经，纬)
     * @return 距离(单位 ： 米)
     */
    Double getDistance(Point2D pointA, Point2D pointB) {
        double EARTH_RADIUS = 6371393; // 平均半径,单位：m
        // 经纬度（角度）转弧度。弧度用作参数，以调用Math.cos和Math.sin
        double radiansAX = Math.toRadians(pointA.getX()); // A经弧度
        double radiansAY = Math.toRadians(pointA.getY()); // A纬弧度
        double radiansBX = Math.toRadians(pointB.getX()); // B经弧度
        double radiansBY = Math.toRadians(pointB.getY()); // B纬弧度
        double cos = Math.cos(radiansAY) * Math.cos(radiansBY) * Math.cos(radiansAX - radiansBX)
                + Math.sin(radiansAY) * Math.sin(radiansBY);
        double acos = Math.acos(cos); // 反余弦值
        return EARTH_RADIUS * acos; // 最终结果
    }


}




